package com.example.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class TokenService {

    private static final long TOKEN_EXPIRATION = 30; // Token 过期时间，单位为分钟
    private static final String SECRET_KEY = "199710043636"; // 替换为你的密钥

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public String generateToken(String userId) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + TOKEN_EXPIRATION * 60 * 1000);

        return Jwts.builder()
                .setSubject(userId)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
                .compact();
    }

    public void saveToken(String token, String userId) {
        redisTemplate.opsForValue().set(token, userId, TOKEN_EXPIRATION, TimeUnit.MINUTES);
    }

    public boolean isTokenValid(String token) {
        return redisTemplate.hasKey(token);
    }

    public void deleteToken(String token) {
        redisTemplate.delete(token);
    }

    public String getUserIdFromToken(String token) {
        return (String) redisTemplate.opsForValue().get(token);
    }

    public boolean validateToken(String token) {
        String userId = (String) redisTemplate.opsForValue().get(token);
        return userId != null;
    }
}